package com.hzjy.api.controller;

import com.alibaba.fastjson.JSON;
import com.hzjy.api.beans.HzjyProduct;
import com.hzjy.api.service.BqTokenService;
import com.hzjy.api.service.impl.ApiProductServiceImpl;
import com.hzjy.api.service.impl.BqUserServiceImpl;
import com.hzjy.api.service.impl.HzjyAgreementServiceImpl;
import com.hzjy.api.vo.BqLoginUser;
import com.hzjy.api.vo.BqUser;
import com.hzjy.common.core.controller.ApiBaseController;
import com.hzjy.common.core.domain.AjaxResult;
import com.hzjy.common.enums.DelistingStatusEnum;
import com.hzjy.common.enums.TradingStatusEnum;
import com.hzjy.common.utils.JSONUtil;
import com.hzjy.common.utils.PageData;
import com.hzjy.common.utils.ServletUtils;
import com.hzjy.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 我要挂牌
 *
 * @author
 */

@Api("我要挂牌页")
@RestController
@RequestMapping("/api/myTrading")
public class ApiMyTradingController extends ApiBaseController {
    private static final Logger log = LoggerFactory.getLogger(ApiMyTradingController.class);
    @Autowired
    private BqTokenService bqTokenService;
    @Autowired
    private ApiProductServiceImpl apiProductService;
    @Autowired
    private HzjyAgreementServiceImpl hzjyAgreementService;
    @Autowired
    private BqUserServiceImpl bqUserService;


    @ApiOperation("获取用户挂牌数量及资料信息")
    @PostMapping("/userInfo")
    public AjaxResult myUserInfo() {
        //PageData pd = new PageData();
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        BqUser bqUser = loginUser.getBqUser();
        Long userId = bqUser.getUserId();
        Map map = apiProductService.getTradingStateNum(userId);
        return AjaxResult.success(200, "查询成功", map);
    }

    /**
     * 请求参数 当前页currentPage，类型state(多种用,隔开)   返回：当前页currentPage，总页数totalPage，总条数totalResult 数据
     *
     * @param pd
     * @return
     */
    @ApiOperation("我的挂牌作品和项目列表")
    @PostMapping("/myTrading")
    public AjaxResult myTradingList(@RequestBody PageData pd) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        BqUser bqUser = loginUser.getBqUser();
        Long userId = bqUser.getUserId();
        Object currentPage = pd.get("currentPage");
        Object size = pd.get("size");
        if (currentPage == null) {
            return AjaxResult.error("参数错误");
        }
        Integer page = Integer.parseInt(currentPage.toString());
        if (page < 1) {
            pd.put("currentPage", 0);
        } else {
            pd.put("currentPage", (page - 1) *Integer.parseInt(size.toString()));
        }
        pd.put("size", size == null || pd.getInteger("size") < 1 ? 10 : pd.get("size"));
        pd.put("userId", userId);
        Integer state = Integer.parseInt(pd.get("state").toString());
        List<Integer> statusList = new ArrayList<>();
        if (state == -1) {
            //查询全部
            pd.remove("state");
        } else if (state == 0) {
            //待审核
            statusList.add(TradingStatusEnum.Audit.getCode());
            statusList.add(TradingStatusEnum.FirstTrial.getCode());
            //pd.put("state", TradingStatusEnum.Audit.getCode() + "," + TradingStatusEnum.FirstTrial.getCode());
        } else if (state == 1) {
            //挂牌成功
            statusList.add(TradingStatusEnum.TradingSuccess.getCode());
//            statusList.add(TradingStatusEnum.PartialCompleted.getCode());
//            statusList.add(TradingStatusEnum.Finished.getCode());
//            pd.put("state", TradingStatusEnum.TradingSuccess.getCode() + "," + TradingStatusEnum.PartialCompleted.getCode() + ","
//                    + TradingStatusEnum.Finished.getCode());
        } else if (state == 2) {
            //待签订
            statusList.add(TradingStatusEnum.FinalTrial.getCode());
            statusList.add(TradingStatusEnum.Signing.getCode());
            statusList.add(TradingStatusEnum.SignTimeOut.getCode());
            /*pd.put("state", TradingStatusEnum.FinalTrial.getCode() + "," +
                    TradingStatusEnum.Signing.getCode() + "," +
                    TradingStatusEnum.SignTimeOut.getCode());*/
        } else if (state == 3) {
            //已成交
            pd.put("statusList",statusList);
            statusList.add(TradingStatusEnum.PartialCompleted.getCode());
            statusList.add(TradingStatusEnum.Finished.getCode());
            //pd.put("state", TradingStatusEnum.PartialCompleted.getCode() + "," + TradingStatusEnum.Finished.getCode());
        }
        pd.put("statusList",statusList);
        List<PageData> tradingList = apiProductService.getMyTradingList(pd);
        PageData count = apiProductService.getMyTradingNum(pd);
        Map map = new HashMap();
        map.put("tradeNewsList", tradingList);
        map.put("totalResult", count.get("totalResult"));
        return AjaxResult.success("查询成功", map);
    }

    @ApiOperation("添加挂牌")
    @PostMapping("/addTrading")
    public AjaxResult addTrading(@RequestBody PageData pd) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        //apiProductService.parameterCalibration(pd);
        BqUser bqUser = loginUser.getBqUser();
        Long userId = bqUser.getUserId();
        pd.put("userId", userId);
        //提交状态 0存草稿；1提交审核
        Object saveType = pd.get("saveType");
        if (Integer.parseInt(saveType.toString()) == 0) {
            pd.put("state", TradingStatusEnum.Draft.getCode()); //初次提交状态为待审核
            apiProductService.addTrading(pd);
            return AjaxResult.success("已保存为草稿");
        } else if (Integer.parseInt(saveType.toString()) == 1) {
            pd.put("state", TradingStatusEnum.Audit.getCode()); //初次提交状态为待审核
            apiProductService.addTrading(pd);
            return AjaxResult.success("已提交等待审批");
        }
        return AjaxResult.success();
    }

    @ApiOperation("修改挂牌")
    @PostMapping("/editTrading")
    public AjaxResult editTrading(@RequestBody PageData pd) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        BqUser bqUser = loginUser.getBqUser();
        Long userId = bqUser.getUserId();
        pd.put("userId", userId);
        HzjyProduct hzjyProduct = apiProductService.selectProductInfo(Long.valueOf(pd.get("product_id").toString()));
        if (hzjyProduct == null) {
            return AjaxResult.error("作品未找到,参数错误");
        }
        if (hzjyProduct.getState() > TradingStatusEnum.FinalTrial.getCode()) {
            return AjaxResult.error("当前状态不能修改挂牌信息");
        }
        //提交状态 0存草稿；1提交审核
        Object saveType = pd.get("saveType");
        if (Integer.parseInt(saveType.toString()) == 0) {
            pd.put("state", TradingStatusEnum.Draft.getCode()); //初次提交状态为待审核
            apiProductService.editTrading(pd);
            return AjaxResult.success("已保存为草稿");
        } else if (Integer.parseInt(saveType.toString()) == 1) {
            pd.put("state", TradingStatusEnum.Audit.getCode()); //初次提交状态为待审核
            apiProductService.editTrading(pd);
            return AjaxResult.success("已提交等待审批");
        }

        return AjaxResult.success();
    }


    @ApiOperation("上架")
    @PostMapping("/upTrading")
    public AjaxResult upTrading(@RequestBody PageData pd) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        Object productId = pd.get("product_id");
        if (productId != null) {
            HzjyProduct hzjyProduct = apiProductService.selectProductInfo(Long.valueOf(productId.toString()));
            if (hzjyProduct.getState() >= TradingStatusEnum.TradingSuccess.getCode()) {
                if (hzjyProduct.getUpState() == 1) {
                    log.error("上架失败,该作品已上架.");
                    return AjaxResult.error("上架失败,该作品已上架.");
                }
                apiProductService.upTrading(pd);
                return AjaxResult.success("上架成功");
            } else {
                log.error("上架失败,该作品未挂牌成功.");
                return AjaxResult.error("上架失败,该作品未挂牌成功.");
            }
        } else {
            log.error("参数为空");
            return AjaxResult.error(500, "参数为空");
        }
    }

    @ApiOperation("下架")
    @PostMapping("/lowTrading")
    public AjaxResult lowTrading(@RequestBody PageData pd) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }

        Object productId = pd.get("product_id");
        if (productId != null) {
            HzjyProduct hzjyProduct = apiProductService.selectProductInfo(Long.valueOf(productId.toString()));
            log.info("【1、下架----校验是否是上架状态】:" + hzjyProduct.getUpState());
            if (hzjyProduct.getUpState() != null && hzjyProduct.getUpState() == 1) {
                log.info("【--------校验上架状态通过---------】.");
                //逻辑临时修改为：当挂牌超期下架时，已经摘牌的申请可以继续进行
//                HzjyDelist queryDelist = new HzjyDelist();
//                queryDelist.setProductId(Long.valueOf(productId.toString()));
//                List<HzjyDelist> hzjyDelistList = apiDelistServiceImpl.selectHzjyDelistList(queryDelist);
//                log.info("【2、下架校验是否存在摘牌的申请】:" + JSONUtil.list2json(hzjyDelistList));
//                if (!CollectionUtils.isEmpty(hzjyDelistList)) {
//                    for (HzjyDelist hzjyDelist : hzjyDelistList) {
//                        if (hzjyDelist.getStatus() > DelistingStatusEnum.Reject.getCode() &&
//                                hzjyDelist.getStatus() < DelistingStatusEnum.DelistSuccess.getCode()) {
//                            log.error("【下架查询到有正在摘牌的申请记录，下架失败!】,记录:" + JSONUtil.object2json(hzjyDelist));
//                            return AjaxResult.error("下架失败,该作品有正在摘牌的申请.");
//                        }
//                    }
//                }
//                log.info("【--------下架校验摘牌的申请通过---------】.");
                apiProductService.lowTrading(pd);
                return AjaxResult.success("下架成功");
            } else {
                return AjaxResult.error("下架失败,该作品未上架.");
            }
        } else {
            return AjaxResult.error(500, "参数为空");
        }
    }

    @ApiOperation("查看挂牌信息（包含编辑时数据展示）")
    @PostMapping("/info")
    public AjaxResult getInfo(@RequestBody PageData pd) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        Object productId = pd.get("product_id");
        if (productId != null) {
            HzjyProduct product = apiProductService.getProductInfo(Long.valueOf(productId.toString()));
            return AjaxResult.success("查询成功", product);
        } else {
            return AjaxResult.error(500, "参数为空");
        }
    }

    @ApiOperation("挂牌提交审核")
    @PostMapping("/submitApprove")
    public AjaxResult submitApprove(@RequestBody PageData pd) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        Object productId = pd.get("product_id");
        if (productId != null) {
            HzjyProduct hzjyProduct = apiProductService.selectProductInfo(Long.valueOf(productId.toString()));
            if (hzjyProduct.getState() == TradingStatusEnum.Draft.getCode() ||
                    hzjyProduct.getState() == TradingStatusEnum.Reject.getCode() ||
                    hzjyProduct.getState() == TradingStatusEnum.FirstTrial.getCode()) {
                apiProductService.submitApprove(pd);
                return AjaxResult.success("挂牌提交审核成功");
            } else {
                return AjaxResult.error("挂牌提交审核失败,当前状态不能提交审核.");
            }
        } else {
            return AjaxResult.error(500, "参数为空");
        }
    }

    @ApiOperation("去签订挂牌协议")
    @PostMapping("/getTardingContract")
    public AjaxResult getTardingContract(@RequestBody PageData pd) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        Long userId = loginUser.getBqUser().getUserId();
        BqUser byUserId = bqUserService.findByUserId(userId.toString());
        if (byUserId.getRealNameCertification().equals(2)){
            return AjaxResult.error(500, "请先进行实名认证");
        }
        Object productId = pd.get("productId");
        Integer code = apiProductService.createTradingContract(Long.valueOf(productId.toString()), loginUser.getBqUser().getUserId().toString());
        if (code == 1) {
            return AjaxResult.success("挂牌协议签订中,请等待....");
        } else {
            return AjaxResult.success("挂牌协议签订失败");
        }
    }

    @ApiOperation("挂牌/摘牌协议签订回调地址")
    @PostMapping("/callBackTrading")
    public void callBackTrading(HttpServletRequest request) {
        log.info("【挂牌/摘牌协议签订回调入口】");
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");
            log.info("【挂牌/摘牌协议签订回调结果】:" + result);
            Map mp = JSON.parseObject(result);
            log.info("====【挂牌/摘牌协议签订回调结果json】====" + JSONUtil.map2json(mp));
            Object flowStatus = mp.get("flowStatus");
            Object flowId = mp.get("flowId");
            if (flowId == null || flowStatus == null) {
                return;
            }
            if (StringUtils.equals(flowStatus.toString(), "2")) {
                hzjyAgreementService.closeContract(flowId.toString());
                log.info("=========================挂牌/摘牌协议签订流程结束完成========================");
            } else {
                return;
            }
        } catch (Exception ex) {
            log.error("****************************挂牌/摘牌协议签订回调*************************." + ex.getMessage());
        }
    }
}
